<template>
  <div>
    <!-- 面包削区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="UsersList.query" clearable @clear="usersDataHandle(UsersList)">
            <el-button slot="append" icon="el-icon-search" @click="usersDataHandle(UsersList)"></el-button>
          </el-input>
        </el-col>
        <el-col :span="1">
          <el-button type="primary" @click="addUsers=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 列表区域 -->
      <el-table
        
        :stripe="true"
        :border="true"
        :data="usersData"
        style="width: 100%">
        <el-table-column label="#" width="48" type="index"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="email" label="邮箱" ></el-table-column>
        <el-table-column prop="mobile" label="电话" ></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#409eff"
              inactive-color="#dcdfe6"
              @change="usersStatusChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="changeInfo(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" @click="open(scope.row)"></el-button>
            <el-button type="warning" icon="el-icon-s-tools" @click="allocationRole(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="UsersList.pagenum"
        :page-sizes="[1, 4, 8, 10]"
        :page-size="UsersList.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addUsers"
        width="50%"
        @close="replacementForm" 
        >
        <!-- 添加用户 -->
        <el-form :model="addUsersForm" :rules="addUsersRules" ref="addUsersForm" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUsersForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUsersForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUsersForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addUsersForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 取消/确定 --> 
        <span slot="footer">
          <el-button @click="addUsers = false">取 消</el-button>
          <el-button type="primary" @click="addUsersClick">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户信息 -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="modificationInfo"
        width="50%">
        <el-form :model="infoForm" :rules="infoRules" ref="infoFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="infoForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">  
            <el-input v-model="infoForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="infoForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="modificationInfo = false">取 消</el-button>
          <el-button type="primary" @click="sureChangeInfo">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog
        @close="closeHandle"
        title="分配角色"
        :visible.sync="allocationDialog"
        width="50%">
        <div>
          <p>当前的用户：</p><br/>
          <p>当前的角色：</p><br/>
          <p>分配新角色：
            <el-select v-model="rid" placeholder="请选择">
              <el-option
                v-for="item in rolesListData"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer">
          <el-button @click="allocationDialog = false">取 消</el-button>
          <el-button type="primary" @click="allocationRoleSure">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {UsersListData,ChangeStatusData,AddNewUsersData,ChangeInfoData,DeleteUserData,RoleListData,allocationRolesData} from '@/request/api'
export default {
  name:'Users',
  data(){
    return {
      //用户id
      RoleId:'',
      //分配角色控制
      allocationDialog:false,
      //角色列表
      rolesListData:[],
      //角色id
      rid:'',
      //用户列表数据
      usersData:[],
      //用户数据列表需传参数
      UsersList:{
        query:'',
        pagenum:1,
        pagesize:4
      },
      total:0,
      //控制添加用户对话框
      addUsers:false,
      //修改用户信息
      modificationInfo:false,
      //添加用户绑定对象
      addUsersForm:{
        username:'',
        password:'',
        email:'',
        mobile:''
      },
      //修改用户信息绑定对象
      infoForm:{
        username:'',
        email:'',
        mobile:''
      },
      //
      changeInfoId:'',
      //验证规则
      addUsersRules:{
        username:[
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password:[
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email:[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        mobile:[
          { required: true, message: '请输入手机号', trigger: 'blur' },
          // { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      },
      //修改用户信息绑定对象验证规则
      infoRules:{
        email:[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        mobile:[
          { required: true, message: '请输入手机号', trigger: 'blur' },
          // { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created(){
    this.usersDataHandle(this.UsersList)
  },
  methods:{
    //分配角色窗口关闭重置
    closeHandle(){
      this.rolesListData=[]
      this.rid=''
    },
    //分配角色 
    allocationRole(data){
      RoleListData().then(res=>{
        if(res.meta.status==200){
          this.rolesListData = res.data
        }
      })
      // 用户列表id
      this.RoleId = data.id

      this.allocationDialog=true
    },
    allocationRoleSure(){
      allocationRolesData({
        id:this.RoleId,
        rid:this.rid
      }).then(res=>{
        if(res.meta.status == 200){
          console.log(res);
          this.usersDataHandle(this.UsersList)
          this.$message.success(res.meta.msg)
        }
      })
      this.allocationDialog = false
    },
    //添加用户发送请求
    addUsersClick(){
      this.addUsers = false
      this.$refs.addUsersForm.validate((valid)=>{
        // console.log(valid);
        if(valid==false)return
        AddNewUsersData(this.addUsersForm).then(res=>{
          // console.log(res)
          if(res.meta.status==201){
            this.$message.success(res.meta.msg)
            this.usersDataHandle(this.UsersList)
          }
        })
      })
    },
    //重置对话框表单
    replacementForm(){
      this.$refs.addUsersForm.resetFields()
    },
    //每页条数改变时触发
    handleSizeChange(newSize){
      // console.log(newSize);
      this.UsersList.pagesize = newSize
      this.usersDataHandle(this.UsersList)
    },
    //当前页改变时触发
    handleCurrentChange(nowCurrent){
      console.log(nowCurrent);
      this.UsersList.pagenum = nowCurrent
      this.usersDataHandle(this.UsersList)
    },
    //请求数据函数
    usersDataHandle(item){
      UsersListData(item).then(res=>{
        // console.log(res);
        if(res.meta.status==200){
          this.usersData = res.data.users
          this.total = res.data.total
        }
      })
    },
    //用户状态改变
    usersStatusChange(data){
      // console.log(data);
      ChangeStatusData(data).then(res=>{
        if(res.meta.status==200){
          // console.log(res);
          this.$message.success('修改状态成功')
        }
        if(res.meta.status!==200){
          data.mg_state=!mg_state
          this.$message.error('修改状态失败')
          return
        }
      })
    },
    // 修改用户信息
    changeInfo(data){
      this.modificationInfo=true
      console.log(data);
      this.infoForm = data
      this.changeInfoId = data.id
    },
    sureChangeInfo(){
      this.$refs.infoFormRef.validate(valid=>{
        this.modificationInfo = false
        if(valid==false)return
          ChangeInfoData({
            id:this.changeInfoId,
            email:this.infoForm.email,
            mobile:this.infoForm.mobile
          }).then(res=>{
            if(res.meta.status!==200){
              this.$message.error(res.meta.msg)
              return
            }
            if(res.meta.status==200){
              this.$message.success(res.meta.msg)
            }
          })
      })
    },
    //删除用户
    open(item) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((data) => {
        if(data=='confirm'){
          DeleteUserData({
            id:item.id
          }).then(res=>{
            if(res.meta.status==200){
              console.log(res);
              this.$message.success(res.meta.msg)
              this.usersDataHandle(this.UsersList)
            }
          })
        }
      }).catch((data_) => {
        if(data_=='cancel'){
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
          return  
        }   
      });
    }
  }
}
</script>

<style scoped lang='less'>
  .el-breadcrumb{
    margin-bottom: 15px;
  }
  .el-card{
    .el-table{
      margin-top: 15px;
        .el-button{
          font-size: 12px;
          width: 20%;
          height: 28px;
          border-radius: 14px;
          position: relative;
          /deep/i{
            position: absolute;left: 50%;top:50%;
            transform: translate(-50%,-50%);
          }
        }
      
    }
    .el-pagination{
      margin-top: 15px;
    }
  }
</style>